!(function (window) {
    var C = {};

    /**
     * 工具方法
     * */
    C.Utils = {
        isDOM: ( typeof HTMLElement === 'object' ) ?
            function(obj){ return obj instanceof HTMLElement;} :
            function(obj){return obj && typeof obj === 'object' && obj.nodeType === 1 && typeof obj.nodeName === 'string';},
        bindEvent(obj, event, fn){
            if(obj.attachEvent){
                obj.attachEvent('on'+event, function () {
                    fn.call(obj);
                })
            }else{
                obj.addEventListener(event, fn, false);
            }
        }
    }

    /**
     * input 正则验证
     * 使用示例: onchange = C.InputValidate.isAbc
     * */
    C.InputValidate = {
        //是否为英文字母
        isAbc() {
            var self = event.target;

            if(!/^[a-zA-Z]+$/g.test(self.value)){self.value='';alert('须为英文字母')};
        },
        //是否为整数
        isInteger() {
            var self = event.target;
            if(!/^[-+]?\d*$/g.test(self.value)){self.value='';alert('须为整数');}
        },
        //是否为双精度
        isFloat() {
            var self = event.target;
            if(!/^[-\+]?\d+(\.\d+)?$/g.test(self.value)){self.value='';alert('须为小数');}
        },
        //是否为中文
        isChinese() {
            var self = event.target;
            if(!/^[\u0391-\uFFE5]+$/g.test(self.value)){self.value='';alert('须为中文');}
        },
        //email格式是否正确
        isEmail() {
            var self = event.target;
            if(!/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/g.test(self.value)){self.value='';alert('邮箱格式不正确');}
        },
        //手机号码格式是否正确
        isPhone() {
            var self = event.target;
            if(!/^\d{11}$/g.test(self.value)){self.value='';alert('手机号码格式不正确');}
        },
        //身份证号码格式是否正确
        isIdCard() {
            var self = event.target;
            if(!/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/g.test(self.value)){self.value='';alert('身份证号格式不正确');}
        },
        //验证任意长度数字
        isLength(len){
            if(len){
                //默认值为0
                len = 0;
            }
            var self = event.target;
            var pattern = new RegExp( "^\\d{"+len+ "}$", "g");
            if(!pattern.test(self.value)){self.value='';alert('须为'+len+'位数字');}
        },
        //是否含有特殊字符
        isSpecialChar(){
            var self = event.target;
            if(!/^[\u4e00-\u9fa5a-z0-9]+$/g.test(self.value)){self.value='';alert('含有特殊字符');}
        }
    }

    /**
     * 省市区三级联动（需要引入 distpickerData.js ）
     * @desc
     * @param province ： 省 dom 元素 id 名称
     * @param city : 市 dom 元素 id 名称
     * @param area : 区 dom 元素 id 名称
     * 使用示例: C.Distpicker.initEle('province', 'city', 'area')
     * */
    C.Distpicker = {

        proEle : null,
        citEle : null,
        areEle : null,

        distpickerData: {
            province: {},
            city: {},
            area: {}
        },

        init(proArr, cityArr, areaArr){

            for(var idx=0;idx<proArr.length;idx++){
                var id = proArr[idx].pk;
                var name = proArr[idx].pv;
                this.distpickerData.province[id] = name;
            }
            for(var idx=0;idx<cityArr.length;idx++){
                var pid = cityArr[idx].pk;
                var id = cityArr[idx].ck;
                var name = cityArr[idx].cv;

                if(!this.distpickerData.city[pid]){
                    this.distpickerData.city[pid] = {};
                }
                this.distpickerData.city[pid][id] = name;
            }

            for(var idx=0;idx<areaArr.length;idx++){
                var cid = areaArr[idx].ck;
                var id = areaArr[idx].cyk;
                var name = areaArr[idx].cyv;

                if(!this.distpickerData.area[cid]){
                    this.distpickerData.area[cid] = {};
                }
                this.distpickerData.area[cid][id] = name;
            }

            console.log(this.distpickerData)
        },
        initEle(proEleId, citEleId, areEleId){
            var proEle = document.getElementById(proEleId);
            var citEle = document.getElementById(citEleId);
            var areEle = document.getElementById(areEleId);

            if(!proEle || !citEle || !areEle){
                throw 'param is null';
                return false;
            }

            if(!C.Utils.isDOM(proEle) || !C.Utils.isDOM(citEle) || !C.Utils.isDOM(areEle)){
                throw 'The parameter [ele] is not html element!';
                return false;
            }

            this.init(proData_,cityData_,countryData_);

            this.proEle = proEle;
            this.citEle = citEle;
            this.areEle = areEle;

            proEle.innerHTML = '';
            var proOption = document.createElement('option');
            proOption.setAttribute('value', '-1');
            proOption.setAttribute('selected', 'selected')
            proOption.innerText = '- 省 -';
            proEle.appendChild(proOption);

            citEle.innerHTML = '';
            var citOption = document.createElement('option');
            citOption.setAttribute('value', '-1');
            citOption.setAttribute('selected', 'selected')
            citOption.innerText = '- 市 -';
            citEle.appendChild(citOption);

            areEle.innerHTML = '';
            var areOption = document.createElement('option');
            areOption.setAttribute('value', '-1');
            areOption.setAttribute('selected', 'selected')
            areOption.innerText = '- 区 -';
            areEle.appendChild(areOption);

            this.initData();
        },

        initData(){
            var p;
            for(p in this.distpickerData.province){
                var proOption = document.createElement('option');
                proOption.setAttribute('value', p);
                proOption.innerText = this.distpickerData.province[p];
                this.proEle.appendChild(proOption);
            }

            var proEle = this.proEle;
            var citEle = this.citEle;
            var areEle = this.areEle;
            var distpickerData = this.distpickerData;
            proEle.onchange = function(){

                var index = proEle.selectedIndex;
                var value = proEle.options[index].value;

                citEle.innerHTML = '';
                areEle.innerHTML = '';

                if(value == -1){

                    var citOption = document.createElement('option');
                    citOption.setAttribute('value', '-1');
                    citOption.setAttribute('selected', 'selected')
                    citOption.innerText = '--- 请选择市 ---';
                    citEle.appendChild(citOption);

                    var areOption = document.createElement('option');
                    areOption.setAttribute('value', '-1');
                    areOption.setAttribute('selected', 'selected')
                    areOption.innerText = '--- 请选择区 ---';
                    areEle.appendChild(areOption);

                    return;
                }

                var citOption = document.createElement('option');
                citOption.setAttribute('value', '-1');
                citOption.setAttribute('selected', 'selected')
                citOption.innerText = '--- 请选择市 ---';
                citEle.appendChild(citOption);

                var c;
                var cIdx = 0;
                for(c in distpickerData.city[value]){

                    var citOption = document.createElement('option');
                    citOption.setAttribute('value', c);
                    if(cIdx == 0){
                        citOption.setAttribute('selected', 'selected');
                    }
                    citOption.innerText = distpickerData.city[value][c];
                    citEle.appendChild(citOption);

                    ++cIdx;
                }

                var areOption = document.createElement('option');
                areOption.setAttribute('value', '-1');
                areOption.setAttribute('selected', 'selected')
                areOption.innerText = '--- 请选择区 ---';
                areEle.appendChild(areOption);

                var aVal = citEle.options[citEle.selectedIndex].value;
                var a;
                var aIdx = 0;
                for(a in distpickerData.area[aVal]){

                    var areOption = document.createElement('option');
                    areOption.setAttribute('value', a);
                    if(aIdx == 0){
                        areOption.setAttribute('selected', 'selected');
                    }
                    areOption.innerText = distpickerData.area[aVal][a];
                    areEle.appendChild(areOption);

                    ++aIdx;
                }
            }

            citEle.onchange = function(){

                var index = citEle.selectedIndex;
                var value = citEle.options[index].value;

                areEle.innerHTML = '';
                if(value == -1){
                    var areOption = document.createElement('option');
                    areOption.setAttribute('value', '-1');
                    areOption.setAttribute('selected', 'selected')
                    areOption.innerText = '--- 请选择区 ---';
                    areEle.appendChild(areOption);

                    return;
                }

                var areOption = document.createElement('option');
                areOption.setAttribute('value', '-1');
                areOption.setAttribute('selected', 'selected')
                areOption.innerText = '--- 请选择区 ---';
                areEle.appendChild(areOption);

                var aVal = citEle.options[citEle.selectedIndex].value;
                var a;
                var aIdx = 0;
                for(a in distpickerData.area[aVal]){

                    var areOption = document.createElement('option');
                    areOption.setAttribute('value', a);
                    if(aIdx == 0){
                        areOption.setAttribute('selected', 'selected');
                    }
                    areOption.innerText = distpickerData.area[aVal][a];
                    areEle.appendChild(areOption);

                    ++aIdx;
                }

            }
        },

        initDefineData(option){
            var _provinceId = option['pId'];
            var _cityId = option['cId'];
            var _areaId = option['aId'];

            var _provinceName = this.getProinceNameById(_provinceId);
            var _cityName = this.getCityNameById(_provinceId, _cityId);
            var _areaName = this.getAreaNameById(_cityId, _areaId);

            var proOption = document.createElement('option');
            proOption.setAttribute('value', _provinceId);
            proOption.setAttribute('selected', 'selected')
            proOption.innerText = _provinceName;
            this.proEle.appendChild(proOption);

            var proOption = document.createElement('option');
            proOption.setAttribute('value', _cityId);
            proOption.setAttribute('selected', 'selected')
            proOption.innerText = _cityName;
            this.citEle.appendChild(proOption);

            var proOption = document.createElement('option');
            proOption.setAttribute('value', _areaId);
            proOption.setAttribute('selected', 'selected')
            proOption.innerText = _areaName;
            this.areEle.appendChild(proOption);
        },
        getProinceNameById(id){
            return this.distpickerData.province[id];
        },
        getCityNameById(pid, id){
            return this.distpickerData.city[pid][id];
        },
        getAreaNameById(cid, id){
            return this.distpickerData.area[cid][id];
        }


    }

    /**
     * 倒计时
     * */
    C.Countdown = {
        /**
         * 根据传入的 day、hour、minute、second、milliSeconds 开始倒计时
         * @desc 调用该方法，传入对象参数，参数为倒计时的 天、时、分、秒，必须为整数
         * @param option(Object)
         * @param day : 天
         * @param hour : 时
         * @param minute : 分
         * @param second : 秒
         * @param milliSeconds : 毫秒
         * @param ele : 元素节点
         * 使用示例: C.Countdown.startByDHMS({
                day : 100,
                hour : 100,
                minute : 100,
                second : 100,
                milliSeconds : 100,
                ele : document.getElementById('countdown'),
                hEle,
                mEle,
                sEle
            })
         * */
        startByDHMS(option) {
            var _dayParam = option['day'] || 0;
            var _hourParam = option['hour'] || 0;
            var _minuteParam = option['minute'] || 0;
            var _secondParam = option['second'] || 0;
            var _milliSecondsParam = option['milliSeconds'] || 0;
            var _ele = option['ele'];
            var _hEle = option['hEle'];
            var _mEle = option['mEle'];
            var _sEle = option['sEle'];

            //判断传入的节点是否正确
            // if (!C.Utils.isDOM(_ele)) {
            //     throw 'The parameter [ele] is not html element!';
            // }

            var date = new Date();
            var _oldTime = date.getTime();
            var _newTime = date.getTime();

            var _totalSecondsParam = 0;
            if (_dayParam && !isNaN(_dayParam) && _dayParam > 0) {
                _totalSecondsParam += _dayParam * 24 * 60 * 60 * 1000
            }

            if (_hourParam && !isNaN(_hourParam) && _hourParam > 0) {
                _totalSecondsParam += _hourParam * 60 * 60 * 1000;
            }

            if (_minuteParam && !isNaN(_minuteParam) && _minuteParam > 0) {
                _totalSecondsParam += _minuteParam * 60 * 1000;
            }

            if (_secondParam && !isNaN(_secondParam) && _secondParam > 0) {
                _totalSecondsParam += _secondParam * 1000;
            }

            if (_milliSecondsParam && !isNaN(_milliSecondsParam) && _milliSecondsParam > 0) {
                _totalSecondsParam += _milliSecondsParam;
            }

            //倒计时时间设置没有差值
            if (_totalSecondsParam == 0) {
                return false;
            }
            _newTime = _oldTime - _totalSecondsParam;

            var _oldDate = new Date();
            var countDownInterval = window.setInterval(function () {
                var _nowDate = new Date();
                var _milliseconds = _nowDate - _oldDate;
                var _addTime = _newTime + _milliseconds;
                if (_addTime <= _oldTime) {
                    var _cdDay = Math.floor((_oldTime - _addTime) / 1000 / 60 / 60 / 24);
                    var _cdHour = Math.floor(((_oldTime - _addTime) / 1000 / 60 / 60) % 24);
                    var _cdMinutes = Math.floor(((_oldTime - _addTime) / 1000 / 60) % 60);
                    var _cdSecond = Math.floor(((_oldTime - _addTime) / 1000) % 60);
                    var _cdMilliseconds = Math.floor((_oldTime - _addTime) % 1000);

                    if (_cdDay >= 0) {
                        _cdDay.toString().length == 1 ? _cdDay = "0" + _cdDay : _cdDay = _cdDay;
                    } else {
                        _cdDay = 0;
                    }

                    if (_cdHour >= 0) {
                        _cdHour.toString().length == 1 ? _cdHour = "0" + _cdHour : _cdHour = _cdHour;
                    } else {
                        _cdHour = 0;
                    }

                    if (_cdMinutes >= 0) {
                        _cdMinutes.toString().length == 1 ? _cdMinutes = "0" + _cdMinutes : _cdMinutes = _cdMinutes;
                    } else {
                        _cdMinutes = 0;
                    }

                    if (_cdSecond >= 0) {
                        _cdSecond.toString().length == 1 ? _cdSecond = "0" + _cdSecond : _cdSecond = _cdSecond;
                    } else {
                        _cdSecond = 0;
                    }

                    if (_cdMilliseconds >= 0) {
                        _cdMilliseconds.toString().length == 1 ? _cdMilliseconds = "00" + _cdMilliseconds : _cdMilliseconds = _cdMilliseconds;
                        _cdMilliseconds.toString().length == 2 ? _cdMilliseconds = "0" + _cdMilliseconds : _cdMilliseconds = _cdMilliseconds;
                    }

                    _hEle.textContent = _cdHour;
                    _mEle.textContent = _cdMinutes;
                    _sEle.textContent = _cdSecond;

                    //补0
                    if (_ele && (_ele.textContent || _ele.textContent.trim() == "")) {
                        _ele.textContent = _cdDay + "  -  " + _cdHour + "-" + _cdMinutes + "-" + _cdSecond + "-" + _cdMilliseconds;
                    }
                } else {
                    //倒计时结束
                    window.clearInterval(countDownInterval);
                }
            }, 1);
        },

        /**
         * 根据传入的 second开始倒计时
         * @desc 调用该方法，传入对象参数，参数为倒计时的 天、时、分、秒，必须为整数
         * @param option(Object)
         * @param second : 秒
         * @param ele : 元素节点
         * 使用示例: C.Countdown.startBySecond({
                ele: document.getElementById('countdown'),
                second: 60
            })
         * */
        startBySecond(option) {

            var _secondParam = option['second'] || 0;
            var _ele = option['ele'];

            //判断传入的节点是否正确
            if (!C.Utils.isDOM(_ele)) {
                throw 'The parameter [ele] is not html element!';
            }

            var date = new Date();
            var _oldTime = date.getTime();
            var _newTime = date.getTime();
            var _totalSecondsParam = 0;

            if (_secondParam && !isNaN(_secondParam) && _secondParam > 0) {
                _totalSecondsParam += _secondParam * 1000;
            }

            //倒计时时间设置没有差值
            if (_totalSecondsParam == 0) {
                return false;
            }
            _newTime = _oldTime - _totalSecondsParam;

            var _oldDate = new Date();
            var countDownInterval = window.setInterval(function () {
                var _nowDate = new Date();
                var _milliseconds = _nowDate - _oldDate;
                var _addTime = _newTime + _milliseconds;
                if (_addTime <= _oldTime) {
                    var _cdSecond = Math.floor(((_oldTime - _addTime) / 1000) % 60);

                    if (_cdSecond >= 0) {
                        _cdSecond.toString().length == 1 ? _cdSecond = "0" + _cdSecond : _cdSecond = _cdSecond;
                    } else {
                        _cdSecond = 0;
                    }

                    //补0
                    if (_ele && (_ele.textContent || _ele.textContent.trim() == "")) {
                        _ele.textContent =  _cdSecond;
                    }
                } else {
                    //倒计时结束
                    window.clearInterval(countDownInterval);
                }
            }, 1);
        },

        /**
         * 获取验证码倒计时
         * 使用示例: C.Countdown.startOfVCode({
                second: 60,
                ele: document.getElementById('getVCode1'),
                before: function () {
                    alert('before')
                },
                after: function () {
                    alert('after')
                }
            })
         * */
        startOfVCode(option) {
            var _secondParam = option['second'] || 0;
            var _beforeFnParam = option['before'] || null;
            var _afterFnParam = option['after'] || null;
            var _ele = option['ele'];

            if(_beforeFnParam && typeof _beforeFnParam != 'function'){
                throw 'before is not function';
            }
            if(_afterFnParam && typeof _afterFnParam != 'function'){
                throw 'after is not function';
            }
            if (!C.Utils.isDOM(_ele)) {
                throw 'ele is not element!';
            }

            //调前置通知
            _beforeFnParam();
            if(_ele.nodeName == 'BUTTON'){
                _ele.innerText = _secondParam+'(s)';
            }else if(_ele.nodeName == 'INPUT'){
                _ele.value = _secondParam+'(s)';
            }
            _ele.disabled = true;
            var _Interval = window.setInterval(()=>{
                --_secondParam;
                if(_secondParam<0){
                    //调后置通知
                    _afterFnParam();
                    if(_ele.nodeName == 'BUTTON'){
                        _ele.innerText = '获取验证码';
                    }else if(_ele.nodeName == 'INPUT'){
                        _ele.value = '获取验证码';
                    }
                    window.clearInterval(_Interval);
                    _ele.disabled = false;
                }else{
                    if(_ele.nodeName == 'BUTTON'){
                        _ele.innerText = _secondParam+'(s)';
                    }else if(_ele.nodeName == 'INPUT'){
                        _ele.value = _secondParam+'(s)';
                    }
                }
            },1000)
        }
    }

    /**
     * 账号操作
     * @desc
     * */
    const accountFiledName = "ACCOUNT";
    const passwordFiledName = "PASSWORD";
    C.AccountUtils = {
        save: function (account, password) {
            this.isCompatible();
            window.localStorage.setItem(accountFiledName, account);
            window.localStorage.setItem(passwordFiledName, password);
        },
        get: function () {
            this.isCompatible();
            var account = window.localStorage.getItem(accountFiledName) || null,
                password = window.localStorage.getItem(passwordFiledName) || null;

            return {account:account, password:password};
        },
        clear: function () {
            this.isCompatible();
            window.localStorage.removeItem(accountFiledName);
            window.localStorage.removeItem(passwordFiledName);
        },
        show: function(accountDom, passwordDom){

            this.isCompatible();
            accountDom.value = this.get().account;
            passwordDom.value = this.get().password;
        },
        isCompatible: function () {
            if(!window.localStorage){
                throw '您的浏览器不支持 localStorage';
                return false;
            }
        }
    }

    //绑定事件，兼容 ie
    function bindEvent(obj, event, fn){
        if(obj.attachEvent){
            obj.attachEvent('on'+event, function () {
                fn.call(obj);
            })
        }else{
            obj.addEventListener(event, fn, false);
        }
    }

    //获取鼠标 x y 坐标
    C.getPos = function(dom){
        var oPos = {x:0, y:0};

        bindEvent(dom, 'mousemove', function (ev) {

            var oEvent = ev || event, x, y;
            if(oEvent.pageX || oEvent.pageY){
                x = oEvent.pageX;
                y = oEvent.pageY;
            }else{
                x = oEvent.clientX + document.body.scrollLeft || document.documentElement.scrollLeft;
                y = oEvent.clientY + document.body.scrollTop || document.documentElement.scrollTop;
            }
            x-=dom.offsetLeft;
            y-=dom.offsetTop;
            oPos.x = x;
            oPos.y = y;
        });
        return oPos;
    }

    //获取随机 rgb 颜色
    C.getRandomColor = function () {
        var r = Math.floor(Math.random() * 256);
        var g = Math.floor(Math.random() * 256);
        var b = Math.floor(Math.random() * 256);
        return "rgb(" + r + "," + g + "," + b + ")";
    }

    //图形化验证码
    C.ValidatePic = function (dom) {

        if(!dom || !dom instanceof HTMLElement){
            throw '您传入的参数不是 dom 元素节点';
            return false;
        }

        dom.innerHTML = '';

        var width = dom.clientWidth,
            height = dom.clientHeight,
            vc = document.createElement('canvas'),
            ctx = vc.getContext('2d'),
            chars = ['a','b','c','d','e','f','g','h','i','j','k','m','n','p','q','r','s','t','u','v','w','x','y','z',
                'A','B','C','D','E','F','G','H','J','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y','Z',
                '0','2','3','4','5','6','7','8','9'],
            totalNum = 4,         //字符数量
            interfereNum = 10,    //干扰线条数量
            pointNum = 100,       //干扰点数量
            vStr = "";            //验证码字符串

        vc.innerText = "您的浏览器可能不支持 canvas";
        vc.width = width;
        vc.height = height;
        dom.appendChild(vc);

        //干扰线条
        for(var idx=0;idx<interfereNum;idx++){
            ctx.beginPath();
            ctx.strokeStyle = C.getRandomColor();
            ctx.moveTo(Math.random()*width, Math.random()*height);
            ctx.lineTo(Math.random()*width, Math.random()*width);
            ctx.closePath();
            ctx.stroke();
        }

        //干扰点
        for(var idx=0;idx<pointNum;idx++){
            var ix = Math.random()*width,
                iy = Math.random()*height;
            ctx.beginPath();
            ctx.strokeStyle = C.getRandomColor();
            ctx.moveTo(ix, iy);
            ctx.lineTo(ix+1, iy+1);
            ctx.closePath();
            ctx.stroke();
        }

        //验证码
        for(var idx=0;idx<totalNum;idx++){
            var str = chars[Math.floor(Math.random()*chars.length)],
                deg = Math.random() * 45 * Math.PI / 180,//产生0~30之间的随机弧度
                x = 0,
                y = 0;
            vStr += str;

            //字的坐标
            x = 8+idx*20;
            y = height/2 + Math.random()*8;

            ctx.beginPath();
            ctx.translate(x,y);
            ctx.rotate(deg);
            ctx.font = "bolder 24px 微软雅黑";
            ctx.fillStyle = C.getRandomColor();
            ctx.fillText(str, 0, 0);
            ctx.closePath();

            ctx.rotate(-deg);
            ctx.translate(-x, -y);
        }

        return vStr;
    }

    //图形化滑块验证码
    C.ValidateSliderPic = function (dom, imgPath) {
        if(!dom || !dom instanceof HTMLElement){
            throw '您传入的参数不是 dom 元素节点';
            return false;
        }

        var width = dom.clientWidth,
            height = dom.clientHeight,
            canvas = document.createElement("canvas"),
            ctx = canvas.getContext("2d"),
            sCanvas = document.createElement("canvas"),
            sCtx = sCanvas.getContext("2d");

        canvas.width = width;
        canvas.height = height;
        canvas.innerText = "您的浏览器可能不支持 canvas";

        sCanvas.width = width;
        sCanvas.height = height;
        sCanvas.innerText = "您的浏览器可能不支持 canvas";

        dom.appendChild(canvas);
        dom.appendChild(sCanvas);

        var rectX = 120, rectY = 50, rectW = 50, rectH = 50, arcR = 10, PI = Math.PI;

        var img = new Image();
        img.src = imgPath;
        img.onload = function () {
            ctx.drawImage(img,0,0,width,height);
            sCtx.drawImage(img,0,0,width,height);

            var cw = rectW + arcR*2;
            var cy = rectY - arcR*2;
            var imgData = sCtx.getImageData(rectX,cy,cw,cw);
            sCanvas.width = cw;
            sCtx.putImageData(imgData,0,cy);
        }

        function drawClip(c, operation){
            //矩形
            c.beginPath();
            c.moveTo(rectX,rectY);
            c.rect(rectX,rectY,rectW,rectH);

            //上圆
            c.moveTo(rectX+rectW/2,rectY-arcR);
            c.arc(rectX+rectW/2,rectY-arcR,arcR,0,360*PI/180,false);

            //右圆
            c.moveTo(rectX+rectW+arcR,rectY+rectH/2);
            c.arc(rectX+rectW+arcR,rectY+rectH/2,arcR,0,360*PI/180,false);
            c.closePath();
            c[operation]();

            //左圆
            c.beginPath();
            c.moveTo(rectX,rectY+rectH/2);
            c.arc(rectX+arcR,rectY+rectH/2,arcR,0,360*Math.PI/180,false);
            c.globalCompositeOperation = "xor";
            c.fill();
        }
        drawClip(ctx, "fill");
        drawClip(sCtx, "clip");
    }

    //刮刮卡
    C.Lottery = function (dom) {

        if(!dom || !dom instanceof HTMLElement){
            throw '您传入的参数不是 dom 元素节点';
            return false;
        }

        var width = dom.clientWidth,
            height = dom.clientHeight,
            canvas = document.createElement("canvas"),
            ctx = canvas.getContext("2d");

        canvas.innerText = "您的浏览器可能不支持 canvas";
        canvas.width = width;
        canvas.height = height;
        dom.appendChild(canvas);

        //创建蒙层
        ctx.beginPath();
        ctx.fillStyle = "#9a9a9a";
        ctx.closePath();
        ctx.fillRect(0,0,width,height);

        //绑定刮卡事件(兼容移动端和 pc 端写法)
        var hastouch = "ontouchstart" in window ? true : false,
            tapstart = hastouch ? "touchstart" : "mousedown",
            tapmove = hastouch ? "touchmove" : "mousemove",
            tapend = hastouch ? "touchend" : "mouseup";

        var points = [],
            x,
            y,
            isDown = false;

        canvas.addEventListener(tapstart,function (e) {
            isDown = true;
            x = hastouch ? e.targetTouches[0].pageX : e.clientX - this.offsetLeft;
            y = hastouch ? e.targetTouches[0].pageY : e.clientY - this.offsetTop;
            points.push([x,y]);
            eraser(ctx);
        },false);

        canvas.addEventListener(tapmove,function (e) {
            if(!isDown){
                return false;
            }
            x = hastouch ? e.targetTouches[0].pageX : e.clientX - this.offsetLeft;
            y = hastouch ? e.targetTouches[0].pageY : e.clientY - this.offsetTop;
            points.push([x,y]);
            eraser(ctx);
        },false);

        canvas.addEventListener(tapend,function () {
            isDown = false;
            points = [];
        },false);

        function eraser(ctx){
            ctx.save();
            ctx.beginPath();
            ctx.moveTo(points[0][0], points[0][1]);
            ctx.lineCap = "round";
            ctx.lineJoin = "round";
            ctx.lineWidth = 30;
            ctx.globalCompositeOperation = "destination-out";
            if(points.length == 1){
                ctx.lineTo(points[0][0] + 1, points[0][1] + 1);
            }else{
                for(var idx=0;idx<points.length;idx++){
                    ctx.lineTo(points[idx][0], points[idx][1]);
                    ctx.moveTo(points[idx][0], points[idx][1]);
                }
            }
            ctx.closePath();
            ctx.stroke();
            ctx.restore();
        }

        //刮开面积的比例
        function proportion(ctx){
            var total = 0,
                count = 0,
                imgData,
                data;
            imgData = ctx.getImageData(0,0,width,height);
            data = imgData.data;
            for(var idx=0;idx<data.length;idx+=4){
                var a = data[idx+3];
                if(a == 0){
                    count += 1;
                }
                total += 1;
            }

            return count/total;
        }
    }

    window.C = C;
})(window)